import sqlite3
import time
import LConf
conf = {}

# 统计
'''
stat = {
    "total" : 0,      # 总请求数
    "totaltime" :0,   # 总时间
    "succ" : 0,       # 成功数
    "succRatio": 0,   # 成功率
    "fail" : 0,       # 失败数
    "except": 0,      # 异常数
    "maxtime" : 0,    # 最大响应时间
    "mintime" : 100,  # 最小响应时间
    "slow"    : 0,    # 慢
    "slowRatio": 100, # 慢比率
    "T" : 0           # 线程数
    "data" : 0        # 测试时间
}
'''

# 从数据库获取数据
def getAndAna(conf):
    stat = {}
    conn = sqlite3.connect(conf['db'],check_same_thread=False)
    c = conn.cursor()
    # 查询总量
    stat['total'] = c.execute("SELECT COUNT(*) FROM p").fetchone()[0]
    # 查询成功
    stat['succ'] = c.execute("SELECT COUNT(*) FROM p WHERE code = 200").fetchone()[0]
    stat['except'] = c.execute("SELECT COUNT(*) FROM p WHERE code = 999").fetchone()[0]
    stat['maxtime'] = c.execute("SELECT max(dt) FROM p WHERE code = 200").fetchone()[0]
    stat['mintime'] = c.execute("SELECT min(dt) FROM p WHERE code = 200").fetchone()[0]
    stat['slow']  = c.execute("SELECT count(*) FROM p WHERE code = 200 AND dt > ?",(conf["slowSta"],)).fetchone()[0]
    stat['T'] = c.execute("SELECT thread FROM info WHERE count = (SELECT max(count) FROM info)").fetchone()[0]
    stat['data'] = c.execute("SELECT etime FROM info WHERE count = (SELECT max(count) FROM info)").fetchone()[0]
    stat["totaltime"] =  c.execute("SELECT sum(dt) FROM p WHERE code = 200").fetchone()[0]
    stat["fail"] = stat['total'] - stat['succ'] - stat['except']
    # 计算比率
    stat["succRatio"] = stat['succ']/stat['total'] * 100
    stat['slowRatio'] = stat['slow']/stat['total'] * 100
    stat['aveTime']   = stat['totaltime']/stat['total']
    return stat
# 打印结果
def resPrint(stat,conf):
    lines = []
    lines.append(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(stat['data'])))
    lines.append('==================================')
    lines.append("总量: %d | 成功: %d | 失败: %d |异常: %d | 成功率 %.2f"%(stat['total'], stat["succ"], stat["fail"], stat['except'],stat['succRatio'])+"%")
    lines.append("最小时间: %.2fms | 最大时间: %.2fms "%(stat['mintime']*1000, stat["maxtime"]*1000))
    lines.append("慢连接数量(>%dms): %d | 慢链接占比:%.3f"%(conf['slowSta'], stat["slow"], stat['slowRatio'])+"%")
    lines.append("总时间： %.2fs |平均时间：%.2fms"%(stat["totaltime"], stat['aveTime']*1000))
    lines.append("线程数：%d"%stat['T'])
    for one in lines: print(one)
    wStr = ''
    # 写到日志
    with open(conf['log'],'a') as fp:
        for one in lines: wStr += one+'\n'
        fp.write(wStr+'\n')

if __name__ == '__main__' :
    # 引入日志
    conf = LConf.LConf('conf.json')
    res = getAndAna(conf)
    resPrint(res,conf)
